package leetcode.code0752;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	int[] nexts = new int[] { 9, 1 };

	public int openLock(String[] deadends, String target) {
		if (target.equals("0000")) {
			return 0;
		}
		Set<String> hash = new HashSet<>();
		for (String string : deadends) {
			if (string.equals("0000")) {// 这用例，是个狠人
				return -1;
			}
			hash.add(string);
		}
		Map<String, Integer> dists = new HashMap<>();
		Queue<String> queue = new LinkedList<>();
		queue.add("0000");
		dists.put("0000", 0);
		while (!queue.isEmpty()) {
			String cur = queue.poll();
			int nextDist = dists.get(cur) + 1;
			char[] cs = cur.toCharArray();
			for (int i = 0; i < 4; i++) {
				char c = cs[i];
				int numc = c - '0';
				for (int j = 0; j < 2; j++) {
					cs[i] = (char) (((nexts[j] + numc) % 10) + '0');
					String tmp = new String(cs);
					if (target.equals(tmp)) {
						return nextDist;
					}
					if (!dists.containsKey(tmp) && !hash.contains(tmp)) {
						dists.put(tmp, nextDist);
						queue.add(tmp);
					}
				}
				cs[i] = c;
			}

		}
		return -1;
	}

	@Override
	public void debug4() {
		HelpDebug.compare(6, this.openLock(HelpDebug.str2array2("[\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"]"), "0202"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
